//
//  GYLockListViewController.m
//  LockManagement
//
//  Created by apple on 2018/7/26.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYLockListViewController.h"
#import "GYLockListHeadView.h"
#import "GYLockListTableViewCell.h"
#import "GYLock.h"
#import "GYNetWorkTools.h"
#import "GYLockAutoAlertView.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "GYBleDataManager.h"
#import "GYBleOperationManager.h"
#import "GYSpeechSynthesizerTool.h"
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>


@interface GYLockListViewController ()<UITableViewDelegate, UITableViewDataSource,BMKLocationServiceDelegate>

/** lockList表格 */
@property (nonatomic, strong) UITableView *lockListTbaleView;

/** 表格数据源 */
@property (nonatomic, strong) NSArray *lockListArrays;

/** 缓存打开或则关闭 */
@property (nonatomic, strong) NSMutableDictionary *cachesHeadState;

/** 当前用户的所在位置 */
@property (nonatomic, assign) CLLocationCoordinate2D coor;

/** 当前定位对象 */
@property (nonatomic, strong) BMKLocationService *locationService;

/** ble */
@property (nonatomic, strong) GYBleOperationManager *operationManager;

/** 当前编码的锁具 */
@property (nonatomic, strong) GYLock *currentLock;
@end

@implementation GYLockListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.lockListTbaleView.frame = self.view.bounds;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.locationService.delegate = self;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveMessage:) name:BLEReceeiveMessage object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.locationService.delegate = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self name:BLEReceeiveMessage object:nil];
}

- (void)receiveMessage:(NSNotification *)noti {
    NSLog(@"receiveessage============%@",noti.object);
    //解析收到的数据
    NSData *messageData = noti.object;

    //1.取得命令编号 判断是那条命令
    NSData *headData = [messageData subdataWithRange:NSMakeRange(2, 1)];
    int title = [[GYBleDataManager convertDataToHexStr:headData] intValue];
    
    //2.去除内容
    NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
    if (title == 2) {
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"SDtt6789" iv:nil error:nil];
        int type = [[GYBleDataManager convertDataToHexStr:decryptData] intValue];
        GYSpeechSynthesizerTool *tools = [[GYSpeechSynthesizerTool alloc] init];
        if (type == 1) {
            NSLog(@"初始化锁具成功==========");
            //在发送锁具编码的网络请求
            [self.currentLock lockCode:self.currentLock.lockID lng:self.coor.longitude lat:self.coor.latitude success:^(BOOL success) {
                if (success) {
                    [SVProgressHUD showSuccessWithStatus:@"编码锁具成功!"];
                    
                    [tools textToSpeechConversion:@"初始化锁具成功!"];
                    //编码成功之后需要重新刷新数据
                    [self loadLockListsData];
                }else {
                    [SVProgressHUD showErrorWithStatus:@"编码锁具失败!"];
                }
            } error:^(NSError *error) {
                
            }];
        }else if (type == 2) {
            NSLog(@"锁具已安装,不允许修改初始秘钥");
            [tools textToSpeechConversion:@"锁具已安装,不允许修改初始秘钥!"];
        }
    }
}

- (void)setupUI {
    self.lockName = @"";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.lockListTbaleView];
    
    //加载数据
    [self loadLockListsData];
    
    //添加上啦刷新
    self.lockListTbaleView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLockListsData)];
    
    //开启定位
    self.locationService = [[BMKLocationService alloc] init];
    [self.locationService startUserLocationService];
}

/**
 加载锁具列表数据
 */
- (void)loadLockListsData {
    [GYLock getLockListsWithlockName:self.lockName current:@"" pageSize:@"" success:^(NSArray *locklists) {
        [self.lockListTbaleView.mj_header endRefreshing];
        self.lockListArrays = locklists;
        [self.lockListTbaleView reloadData];
    } error:^(NSError *error) {
        
    }];
}

- (void)setLockName:(NSString *)lockName {
    _lockName = lockName;
    
    NSLog(@"_lockName==========%@",lockName);
    //然后加载数据显示数据
    [self loadLockListsData];
}

#pragma mark -- UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.lockListArrays.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    GYLock *model = self.lockListArrays[section];
    
    //1.取缓存中的数据
    BOOL isOpen = [self.cachesHeadState[model.lockID] boolValue];
    return isOpen ? 1 : 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYLockListTableViewCell *cell = [GYLockListTableViewCell cellWithTableView:tableView];
    cell.model = self.lockListArrays[indexPath.section];
    kWeakSelf(self)
    cell.lockActionCallBack = ^(NSInteger tag, GYLock *lock) {
        switch (tag) {
            case 1:
                {
                    NSLog(@"锁具路线导航...");
                    if (!lock.lockState) {
                        [SVProgressHUD showInfoWithStatus:@"该锁具还未编码,请先编码!"];
                        return ;
                    }
                    [weakself planingRoute:lock];
                    //weakself.planningRouteCallBack();
                    
                    //1.发送一个通知  规划路线
                    //[[NSNotificationCenter defaultCenter]postNotificationName:@"planningRoute" object:lock];
                }
                break;
                
            case 2:
            {
                NSLog(@"锁具申请授权...");
                GYLockAutoAlertView *authoAlertView = [GYLockAutoAlertView initWithFrame:[UIScreen mainScreen].bounds];
                authoAlertView.lockID = lock.lockID;
                [[[UIApplication sharedApplication] keyWindow] addSubview:authoAlertView];
            }
                break;
                
            case 3:
            {
                NSLog(@"编码...");
                //需要判断要是是否是连接状态
                if (self.operationManager.connectType != deviceConntTypeSuccess) {
                    [SVProgressHUD showInfoWithStatus:@"蓝牙设备未连接,请先连接蓝牙设备!"];
                    return;
                }
                //编码的时候需要发送 一个初始化锁的信息
                NSData *data = [GYBleDataManager setupLock];
                [self sendMessageData:data];
                
                self.currentLock = lock;
            }
                break;
                
            default:
                break;
        }
    };

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    GYLockListHeadView *headView = [GYLockListHeadView headViewWithTableView:tableView];
    GYLock *tempModel = self.lockListArrays[section];
    headView.model = tempModel;
    headView.open = [self.cachesHeadState[tempModel.lockID] boolValue];
    kWeakSelf(self)
    headView.headViewBtnClickCallBack = ^(GYLock *model){
        
        BOOL isOpen = [weakself.cachesHeadState[model.lockID] boolValue];
        [weakself.cachesHeadState setObject:@(!isOpen) forKey:model.lockID];
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    };
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 58;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYLockListTableViewCell *cell = [GYLockListTableViewCell cellWithTableView:tableView];
    
    return [cell cellHeight];
}

/**
 吊起百度导航
 */
- (void)planingRoute:(GYLock *)model {
    
    //初始化调启导航时的参数管理类
    BMKNaviPara *para = [[BMKNaviPara alloc]init];
    //实例化线路检索节点信息类对象
    BMKPlanNode *end = [[BMKPlanNode alloc]init];
    //指定终点经纬度
    end.pt = CLLocationCoordinate2DMake(model.lat, model.lng);
    //指定终点名称
    end.name = model.lockName;
    //指定终点
    para.endPoint = end;
    //指定返回自定义scheme
    para.appScheme = @"baidumapsdk://mapsdk.baidu.com";
    //应用名称
    para.appName = @"";
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"打开百度地图客户端" message:@"百度地图-步行导航" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *openAction = [UIAlertAction actionWithTitle:@"开始导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        /**
         调起百度地图客户端步行导航界面
         
         @param para 调起步行导航时传入的参数
         @return 结果状态码
         */
        [BMKNavigation openBaiduMapWalkNavigation:para];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:openAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma 蓝牙的发送数据 处理方法 --- 这个蓝牙收发最多只能20字节,超过20字节的需要自己分段  分成20字节一段开始发送

/**
 针对蓝牙发送的数据做一个分包处理
 
 @param messageData <#messageData description#>
 */
- (void)sendMessageData:(NSData *)messageData {
    if (messageData.length > 20) {
        NSData *contentData;
        int count = messageData.length/20 + 1;
        
        Byte *testByte =(Byte *)[messageData bytes];
        for (int i = 0; i < count; i++) {
            Byte ceshi[20] = {0};
            for (int k=0; k < 20; k++) {
                ceshi[k] = testByte[i*20+k];
            }
            NSData *ceshiData = [NSData dataWithBytes:ceshi length:20];
            [self.operationManager sendMessage:ceshiData];
            [NSThread sleepForTimeInterval:0.01];
        }
    }else {
        [self.operationManager sendMessage:messageData];
    }
}

#pragma mark -- BMKLocationServiceDelegate
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    //NSLog(@"用户更新位置成功....");
    self.coor = userLocation.location.coordinate;
}
#pragma mark -- 懒加载

- (UITableView *)lockListTbaleView {
    if (!_lockListTbaleView) {
        _lockListTbaleView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _lockListTbaleView.delegate = self;
        _lockListTbaleView.dataSource = self;
    }
    
    return _lockListTbaleView;
}

- (NSMutableDictionary *)cachesHeadState {
    if (!_cachesHeadState) {
        _cachesHeadState = [NSMutableDictionary dictionary];
    }
    
    return _cachesHeadState;
}

- (GYBleOperationManager *)operationManager {
    if (!_operationManager) {
        _operationManager = [GYBleOperationManager shareOperationManager];
    }
    return _operationManager;
}









@end
